/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao (cnfree2000@hotmail.com) ***/
package controller;

import entity.Novalchapter;
import entity.Novel;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import service.NovalService;

@Controller
public class NovalAction {

	@Resource
	private NovalService novalService;

	@RequestMapping({ "/addnoval" })
	public String addnoval(Model model, HttpServletRequest request,
			Novel novel, @RequestParam("files") MultipartFile[] files) {
		List novalchapters = new ArrayList();
		Novalchapter novalchapter = null;
		Map map = request.getParameterMap();
		Set set = map.keySet();
		Iterator it = set.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			if (key.startsWith("chaptername")) {
				novalchapter = new Novalchapter();
				String chaptername = ((String[]) map.get(key))[0];
				int chapterid = Integer.parseInt(key.substring(11));
				novalchapter.setChaptername(chaptername);
				novalchapter.setChapterid(chapterid);
				try {
					InputStream in = files[chapterid].getInputStream();
					byte[] bt = new byte[in.available()];
					files[chapterid].getInputStream().read(bt, 0,
							in.available());
					String sb = new String(bt);
					System.out.println(sb);
					novalchapter.setChaptercontent(sb);
				} catch (IOException e) {
					e.printStackTrace();
				}

				novalchapters.add(novalchapter);
			}

		}

		this.novalService.saveNova(novalchapters, novel);
		return "jsonlist";
	}
}